<template>
	<view class="form_box">

		<u-picker :show="show" :columns="columns" @colse="show = false" @confirm="confirm1"></u-picker>
		<u--form labelPosition="top" labelWidth="600rpx" :model="model" :rules="rules" ref="uForm">
			<template v-for="(item,index) in formList">
				<u-form-item :label="item.label" :required="item.required" :prop="item.required?item.value:''" ref="item1" :key="index">
					<template v-if="item.type == 'input'">
						<u--input v-model="model[item.value]" border="surround" :type="item.inpType" :customStyle="{
							'border-radio':'16rpx',
						}" :placeholder="item.placeholder"></u--input>
					</template>
					<template v-else-if="item.type == 'radio'">
						<u-radio-group v-model="model[item.value]" placement="column" style="margin-top: 8rpx;">
							<u-radio :customStyle="{marginBottom: '8px',marginRight:'40rpx'}" activeColor="#50B674"
								v-for="(item, index) in item.selectList" :key="index" :label="item" :name="item">
							</u-radio>
						</u-radio-group>
					</template>
					<template v-else-if="item.type == 'input_phone'">
						<view class="" style="
							width: 100%;
							display: flex;
							border-bottom: 1rpx solid #eee;padding: 24rpx 0;
							align-items: center;">
							<view class="qianzui" @click="handAreaCode">
								{{areaCode}}<u-icon name="arrow-down" color="#ADADAD" size="28rpx"></u-icon>
							</view>
							<u--input v-model="model[item.value]" border="none" type="number"
								:placeholder="item.placeholder" :customStyle="{
							'border-radio':'16rpx',
						}">
								<!-- <view style="width: 90rpx;display: flex;" slot="prefix" @click="handAreaCode">
								{{areaCode}}<u-icon name="arrow-down" color="#ADADAD" size="28rpx"></u-icon>
							</view> -->
							</u--input>
						</view>
					</template>
					<template v-else-if="item.type == 'checkbox'">
						<u-checkbox-group v-model="model[item.value]" placement="column" activeColor="#50B674"
							shape="circle">
							<u-checkbox :customStyle="{marginBottom: '48rpx'}" v-for="(item, index) in item.selectList"
								:key="index" :label="item" :name="item">
							</u-checkbox>
						</u-checkbox-group>
					</template>
					<template v-else-if="item.type == 'textarea'">
						<u--textarea style="margin-top: 16rpx;" :count="true" maxlength="2000"
							v-model="model[item.value]" :placeholder="item.placeholder"></u--textarea>
					</template>
					<template v-else-if="item.type == 'input_address'">
						<!-- 	<u-datetime-picker
								:show="address_show"
								v-model="value1"
								mode="date"
								@close="addressClose"
								@cancel="addressClose"
								@confirm="confirm"
						></u-datetime-picker> -->
						<u-picker :show="address_show" keyName="name" :defaultIndex="defaultSelector" ref="uPicker"
							:columns="address_columns" @confirm="confirmposition" @change="changeHandler"
							@cancel="addressClose" closeOnClickOverlay @close="addressClose"
							@closeOnClickOverlay="true"></u-picker>
						<view style="display: flex;flex-direction: column;">
							<view class="address1_view" @click="clickAddress">
								{{address_p}}
							</view>
							<view style="margin-top: 24rpx;">
								<u--input v-model="model.address" border="surround" type="text" :customStyle="{
									'border-radio':'16rpx',
								}" :placeholder="item.placeholder"></u--input>
							</view>
						</view>
					</template>

					<template v-else-if="item.type == 'file'">
						<view class="view_upload" @click="openUpload">
							<image src="@/static/images/icon_scfjjl.png" mode="" v-if="file_name == '点击上传附件简历'"></image>
							<image src="@/static/images/icon_pdf.png" mode="" v-else-if="file_last == 'pdf'"></image>
							<image src="@/static/images/icon_word.png" mode=""
								v-else-if="file_last != 'pdf' && file_last != ''"></image>
							<!-- 点击上传附件简历 -->
							{{file_name}}
						</view>
						<u--input v-model="model.problem12" border="surround" type="text" :customStyle="{
							'border-radio':'16rpx',
						}" :placeholder="item.placeholder" v-show="false"></u--input>
					</template>

					<template v-else-if="item.type == 'image'">
						<u-upload
							:fileList="fileList1"
							@afterRead="afterRead"
							@delete="deletePic"
							name="1"
							:maxCount="1"
						></u-upload>
					</template>
				</u-form-item>
			</template>
			<view class="explanatory_text">
				注：在填表与认证过程，有任何疑问，请咨询生生老师：sssylaoshi
			</view>
			<view class="" style="width: 100%;height: 200rpx;">

			</view>
			<view class="btn_box">
				<view class="box_btn" @click="submit">
					提交申请
				</view>
			</view>
		</u--form>


	</view>
</template>

<script>
	import helper from '@/common/helper.js';
	import response from "@/static/response.json"
	import config from "@/config"; // 配置文件
	import storage from "@/common/storage.js"; // 缓存封装
	import {
		problem_type,
		form_submit
	} from '@/common/api/problem.js'
	import {
		dianhua
	} from '@/common/api/start.js'
	var AfDocument = uni.requireNativePlugin("Aq-ChooseFile");
	export default {
		props: {
			formList: {
				type: Array,
				default: () => {
					return [{
						type: 'input',
						placeholder: '请输入名字',
						required: true,
						label: '姓名',
						value: 'name',
						inpType: 'text'
					}, {
						type: 'radio',
						required: true,
						label: '性别',
						value: 'sex',
						placeholder: '请选择性别',
						selectList: [{
							name: '男',
							value: 1
						}, {
							name: '女',
							value: 2
						}]
					}, {
						type: 'input',
						required: true,
						placeholder: '请输入年龄',
						label: '年龄',
						value: 'age',
						inpType: 'number'
					}, {
						type: 'input',
						required: true,
						placeholder: '请输入职位',
						label: '职位',
						value: 'position',
						inpType: 'text'
					}, {
						type: 'input',
						required: true,
						placeholder: '请输入公司',
						label: '公司',
						value: 'company',
						inpType: 'text'
					}, {
						type: 'input_phone',
						required: true,
						placeholder: '请输入手机号',
						label: '手机号',
						value: 'phone',
						inpType: 'number'
					}, {
						type: 'input',
						required: true,
						placeholder: '请输入微信号',
						label: '微信号',
						value: 'weChat',
						inpType: 'text'
					}, {
						type: 'input',
						required: true,
						placeholder: '请选择你的地址信息',
						label: '地址',
						value: 'address',
						inpType: 'text'
					}, {
						type: 'input',
						required: false,
						placeholder: '详细地址，如街道、楼层、门牌号等',
						label: '',
						value: 'address',
						inpType: 'text'
					}, {
						type: 'input',
						required: true,
						placeholder: '请输入邮箱',
						label: '邮箱',
						value: 'mailbox',
						inpType: 'text'
					}, {
						type: 'checkbox',
						required: true,
						label: '1、你是何种行者?（可多选）',
						placeholder: '请选择何种行者',
						value: 'nshzxz',
						selectList: [{
							name: '有多年修行经验，有自己的信仰',
							value: 1
						}, {
							name: '书院学员',
							value: 2
						}, {
							name: '冰释老师读者',
							value: 3
						}, {
							name: '刚开展修身之路',
							value: 4
						}, {
							name: '其他',
							value: 5
						}]
					}, {
						type: 'textarea',
						required: true,
						placeholder: '请输入内容',
						label: '2、是什么原因促使你的道路?',
						value: 'ssmyg2',
						inpType: 'text'
					}, {
						type: 'textarea',
						required: true,
						placeholder: '请输入内容',
						label: '3、是什么原因促使你的道路?',
						value: 'ssmyg3',
						inpType: 'text'
					}]
				}
			},
			rules: {
				type: Object,
				default: () => {}
			},
			model: {
				type: Object,
				default: () => {}
			},
			id: {
				type: String,
				default: ''
			},
			type: {
				type: String,
				default: 0
			},
		},
		data() {
			return {
				areaCode: '+86',
				columns: [
					['+86', '+87']
				],
				show: false,
				value1: '',
				address_show: false,
				address_p: '请选择你的地址信息',
				address_columns: [],
				defaultSelector: [0, 0, 0],
				province: [],
				city: [],
				region: [],
				file_name: '点击上传附件简历',
				file_last: '',
				file_id: -1,
				fileList1:[],
			}
		},
		created() {
			this.model.img = ''
			console.log('rulesrules', this.rules, this.formList);
			console.log('response', response.data.list);
			let data = response.data.list;
			let arr = [];
			for (let i in data) {
				arr.push(data[i]);
			}
			this.province = arr;
			this.address_columns[0] = arr;

			let brr = [];
			for (let i in data[1].city) {
				brr.push(data[1].city[i]);
			}
			this.city = brr;
			this.address_columns[1] = brr;

			// this.address_columns[1] = data[1].city;

			let crr = [];
			for (let i in data[1].city[2].region) {
				crr.push(data[1].city[2].region[i]);
			}
			this.region = crr;
			this.address_columns[2] = crr;
			// this.address_columns[2] = data[1].city[2].region


			console.log('address_columns', this.address_columns);
			// this.$nextTick(() => {
			// 	this.formList.forEach((item,index) => {
			// 		console.log('itemitemitem',item.value);

			// 		if (item.type == "input_address") {
			// 			let value = item.value.split(',');
			// 			for (let i =0;i<value.length;i++) {
			// 				this.model1[value[i]] = "";
			// 			}
			// 		} else {
			// 			this.model1[item.value] = "";
			// 		}
			// 	})

			// })

		this.getDianhua();
			console.log('this.model1model1', this.model);
			// setTimeout(() => {
			// 	this.formList.forEach((item,index) => {
			// 		console.log('itemitemitem',item.value);
			// 		this.rules[item.value] = {
			// 				type: 'string',
			// 				required: true,
			// 				message: item.placeholder,
			// 				trigger: ['blur', 'change']
			// 		}
			// 	})

			// },800) 

		},
		methods: {

			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				console.log(this.fileList1,'文件列表')
				this.model.img = ''

			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				let that = this;
      			let token = storage.get("token");
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: config.uni_app_web_api_url + "/api/upload/image", // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						header: {
							"Access-Token": token,
						},
						success: (res) => {
							const data = JSON.parse(res.data);
							this.model.img = data.data.fileInfo.file_id
							console.log(data,'上传成功')
							console.log(this.fileList1,'文件列表')
							resolve(res.data.data)
						}
					});
				})
			},






			getDianhua() {
				dianhua().then(res => {
					console.log('ressss', res);
					this.columns = [res.data.dianhua];
				})
			},
			handAreaCode() {
				this.show = true;
			},
			confirm1(e) {
				this.areaCode = e.value[0].split(' ')[1];
				this.show = false;
			},
			clickAddress() {
				this.address_show = true;
			},
			addressClose() {
				this.address_show = false;
			},
			openUpload() {
				let token = storage.get("token");
				let that = this;
				// paths: ['/storage/emulated/0/Download', '/storage/emulated/0/A', ], //自定义选择目录
				AfDocument.openMode({
					size: '1', //选择总数量
					isDown: true, //是否下钻（true 筛选当前目录以下的所有文件，fales 只筛选当前目录文件） 
					types: [{
						name: '文档',
						value: ["doc", "wps", "docx", "xls", "xlsx", "pdf"]
					}]
				}, (res) => {
					this.data = JSON.stringify(res);
					console.log('resssss', res.res[0].pathHolp);
					uni.uploadFile({
						url: config.uni_app_web_api_url + "/api/upload/annex", //仅为示例，非真实的接口地址
						header: {
							"Access-Token": token,
						},
						filePath: res.res[0].pathHolp,
						name: 'file',
						formData: {
							'user': 'test'
						},
						success: (uploadFileRes) => {
							let data = JSON.parse(uploadFileRes.data);
							let last = data.data.fileInfo.file_name.split('.');

							that.file_last = last[last.length - 1];
							that.file_name = data.data.fileInfo.file_name;
							that.file_id = data.data.fileInfo.file_id;
							that.$emit('upload', that.file_id);
							console.log(data, 'dddddddddddd');
						}
					});
				})
			},
			handUpload() {

				let token = storage.get("token");
				uni.chooseImage({
					success: (chooseImageRes) => {
						console.log('chooseImageRes', chooseImageRes);
						const tempFilePaths = chooseImageRes.tempFilePaths;
						uni.uploadFile({
							url: config.uni_app_web_api_url + "/api/upload/annex", //仅为示例，非真实的接口地址
							header: {
								"Access-Token": token,
							},
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'user': 'test'
							},
							success: (uploadFileRes) => {
								let data = JSON.parse(uploadFileRes.data);
								console.log(data, 'dddddddddddd');
							}
						});
					}
				});
			},
			confirm(e) {
				const time = helper.djsFull(e.value);
				console.log('eeeeee', e, time);
				// this.model.address = `${time.y}-${time.m}-${time.d}`
				this.address_p = `${time.y}-${time.m}-${time.d}`;
				this.address_show = false;
			},
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					indexs,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e;
				let province = this.province[indexs[0]];
				console.log('province', province);
				let city = [];
				let oneItem = '';
				let region = [];
				for (let i in province.city) {
					if (!oneItem) {
						oneItem = i;
					}
					city.push(province.city[i])
				}
				let oneCity = city[0];
				for (let i in oneCity.region) {
					region.push(oneCity.region[i])
				}
				if (columnIndex == 0) {
					console.log('changeeeee', this.province[index], index, city, oneItem, oneCity);
					picker.setColumnValues(1, city);
					picker.setColumnValues(2, region);
				} else if (columnIndex == 1) {
					let region = [];
					let cityItem = city[indexs[1]].region;
					for (let i in cityItem) {
						region.push(cityItem[i]);
					}
					console.log('1111111111', region);
					picker.setColumnValues(2, region)
				}
				console.log('eeeeeee', e);
			},
			confirmposition(e) {
				console.log('eeeeee', e.value);
				let value = e.value;
				this.$emit('address', {
					province_id: value[0].id,
					city_id: value[1].id,
					district_id: value[2].id
				});
				this.address_p = `${value[0].name}-${value[1].name}-${value[2].name}`
				this.address_show = false;
			},
			submit() {
				console.log('type', this.type);
				this.$refs.uForm.validate().then(res => {
					console.log('fffffffffff', {
						link_id: this.id,
						type: this.type,
						...this.model
					});
					form_submit({
						link_id: this.id,
						type: this.type + 1,
						...this.model
					}).then(res => {
						console.log('resssss', res);
						uni.$u.toast('提交成功');
						uni.navigateBack({
							delta: 1
						})
					}).catch(err => {
						console.log('errrrrrr', err);
						uni.$u.toast(err);
					})
					console.log('model1model1', this.model, this.file_id, this.type, this.id);
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.form_box {
		width: 100%;
	}

	.explanatory_text {
		font-size: 30rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		color: #3D3D3D;
		margin-top: 42rpx;
		margin-bottom: 20rpx;
	}

	.btn_box {
		width: 100%;
		height: 200rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		display: flex;
		justify-content: center;
		padding-top: 32rpx;
		box-sizing: border-box;
		background: #fff;

		.box_btn {
			width: 630rpx;
			height: 96rpx;
			background: linear-gradient(360deg, #50B674 0%, #AEDDBD 100%);
			border-radius: 48rpx 48rpx 48rpx 48rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 30rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			color: #FFFFFF;
		}
	}

	.address1_view {
		width: 690rpx;
		border-radius: 16rpx 16rpx 16rpx 16rpx;
		border: 1rpx solid #E5E5E5;
		font-size: 28rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		color: #c0c4cc;
		padding: 18rpx 18rpx;
		box-sizing: border-box;
	}

	.view_upload {
		width: 690rpx;
		border-radius: 16rpx 16rpx 16rpx 16rpx;
		border: 1rpx solid #E5E5E5;
		font-size: 28rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		color: #c0c4cc;
		padding: 18rpx 18rpx;
		box-sizing: border-box;
		display: flex;

		image {
			width: 40rpx;
			height: 40rpx;
			margin-right: 16rpx;
		}
	}
	.qianzui {
		width: 92rpx;
		display: flex;
		align-items: center;
		border-right: 1rpx solid #eee;
		margin-right: 24rpx;
	}
</style>